import cv2
import numpy as np
from PIL import Image

from pythonProject.tools.adb_shell import screenshot_methods


class ImageMatcher:
    def __init__(self, target_img_path, threshold=0.8):
        """
        用于图片匹配的工具类
        :param target_img_path: 目标图片路径
        :param threshold: 匹配相似度阈值
        """
        self.target_img = self._load_image(target_img_path)
        self.threshold = threshold

    @staticmethod
    def _load_image(img_path):
        """
        加载目标图片
        """
        img = cv2.imread(img_path, cv2.IMREAD_COLOR)
        if img is None:
            raise FileNotFoundError(f"目标路径不存在图片: {img_path}")
        print('加载匹配图片成功')
        return img

    def match(self, screenshot):
        """
        使用模板匹配，查找目标图片在截图中的位置
        :param screenshot: 当前截图
        :return: 匹配位置 (x, y, w, h) 或 None
        """
        target_gray = cv2.cvtColor(self.target_img, cv2.COLOR_BGR2GRAY)
        screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)

        # 模板匹配
        res = cv2.matchTemplate(screenshot_gray, target_gray, cv2.TM_CCOEFF_NORMED)
        loc = np.where(res >= self.threshold)

        if len(loc[0]) > 0:
            pt = (loc[1][0], loc[0][0])
            h, w = self.target_img.shape[:2]
            return pt[0], pt[1], w, h
        print('未找到匹配区域')
        return None


class ScreenshotProcessor:
    def __init__(self, area_points):
        """
        截图处理类，用于裁剪和匹配指定区域
        :param area_points: 需要裁剪的区域 (x, y, w, h)
        """
        if len(area_points) != 4:
            raise ValueError("area_points 必须包含 4 个元素")
        self.area_points = area_points
        self.screenshot = None

    def get_screenshot(self):
        if self.screenshot is None:
            try:
                self.screenshot = screenshot_methods()
            except Exception as e:
                print(f"获取截图失败: {e}")
                self.screenshot = None
        return self.screenshot

    def crop_area(self):
        """
        裁剪截图中的指定区域
        :return: 裁剪后的区域图像
        """
        x, y, w, h = self.area_points
        screenshot = self.get_screenshot()
        return screenshot[y:y + h, x:x + w]


def process_image(area_points, img_path, threshold):
    """
    主流程：从截图中裁剪区域并进行图片匹配
    :param area_points: 需要裁剪的区域 (x, y, w, h)
    :param img_path: 目标图片路径
    :param threshold: 匹配相似度阈值
    :return: 匹配位置或 None
    """

    img = cropped_img(area_points)
    # 初始化图像匹配器，用于比较图像相似度
    matcher = ImageMatcher(img_path, threshold)

    # 将裁剪后的图像与目标图像进行匹配，并返回匹配结果
    match_result = matcher.match(img)

    if match_result:
        x_offset, y_offset = area_points[:2]
        adjusted_result = (match_result[0] + x_offset, match_result[1] + y_offset, match_result[2], match_result[3])
        print(f"匹配成功，位置: {adjusted_result}")
        return adjusted_result
    print("匹配失败")
    return None

def cropped_img(area_points):
    try:
        x, y, w, h = area_points
        crop_img = screenshot_methods()[y:y+h, x:x+w]
        pil_image = Image.fromarray(np.uint8(crop_img))
        # pil_image.save("crop_img.png")
    except Exception as e:
        # 记录异常信息，便于调试
        print(f"Error occurred during cropping: {e}")
        return None
    if crop_img is None or crop_img.size == (0, 0):  # 假设 size 是一个元组 (width, height)
        return None

    return pil_image

